﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BusinessLayer.WorldArtPrice;
using BusinessLayer.WorldArtPrice.Entities;
using BackEnd.Models;
using BusinessLayer.WorldArtPrice.Models;
using BackEnd.Common;

namespace BackEnd.Controllers
{
    public class ArtistController : Controller
    {
        private const int PageSize = 20;
        //
        // GET: /Artist/
        [CustomAuthorize(Action = Constants.AdminActions.ViewArtist)]
        public ActionResult Index(string keyword,int? born, int? died, int? country, int? page)
        {
            var subBL = new ArtistBL();
            string keywordValue = (String.IsNullOrEmpty(keyword)) ? "" : keyword;
            int bornValue = (born.HasValue) ? born.Value : -1;
            int diedValue = (died.HasValue) ? died.Value : -1;
            int countryValue = (country.HasValue) ? country.Value : -1;
            int pageValue = (page.HasValue) ? page.Value : 1;
            var lstArtists = new List<BusinessLayer.WorldArtPrice.Models.ArtistForAdminModel>();
            lstArtists.AddRange(subBL.SearchForAdmin(keywordValue, bornValue, diedValue, countryValue, pageValue, PageSize));
            int total = 0;
            //ArtistTotalRecordSearch
            if (pageValue == 1 || Session[Common.Constants.SessionKeys.ArtistTotalRecordSearch] == null)
            {
                subBL.GetTotalRecordsBy(keywordValue, bornValue, diedValue, countryValue, out total);
                Session[Common.Constants.SessionKeys.ArtistTotalRecordSearch] =total;
            }
            else
            {
                total = Convert.ToInt32(Session[Common.Constants.SessionKeys.ArtistTotalRecordSearch]);
            }
            
            var model = new Models.SearchArtistModel();
            model.KeyWord = keyword;
            model.Born = born;
            model.Died = died;
            model.Country = countryValue;
            model.PageIndex = pageValue;
            model.TotalRecord = total;
            model.PageSize = PageSize;
            model.ListOfArtist = lstArtists;
            List<Countrys> listCoutry = new CountryBL().GetAll();
            listCoutry.Insert(0, new Countrys { Id = -1, Country = "All countries ----------" });
            model.ListCountry = listCoutry;
            return View("Index", model);
        }
        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.ViewArtist)]
        public ActionResult Index(SearchArtistModel model)
        {
            

            var subBL = new ArtistBL();
            var lstArtists = new List<BusinessLayer.WorldArtPrice.Models.ArtistForAdminModel>();
            if (ModelState.IsValid)
            {
                string keywordValue = (String.IsNullOrEmpty(model.KeyWord)) ? "" : model.KeyWord;
                int bornValue = (model.Born.HasValue) ? model.Born.Value : -1;
                int diedValue = (model.Died.HasValue) ? model.Died.Value : -1;
                int countryValue = (model.Country>0) ? model.Country : -1;
                int pageValue = (model.PageIndex>1) ? model.PageIndex: 1;

                return RedirectToAction("Index", "Artist", new { keyword = Server.UrlEncode(keywordValue), born = (bornValue < 0) ? String.Empty : bornValue.ToString(), died = (diedValue < 0) ? String.Empty : diedValue.ToString(), country = (countryValue < 0) ? String.Empty : countryValue.ToString(), pageIndex = 1 });
                
            }
            List<Countrys> listCoutry = new CountryBL().GetAll();
            listCoutry.Insert(0, new Countrys { Id = -1, Country = "All countries ----------" });
            model.ListCountry = listCoutry;
            model.PageIndex = 0;
            model.TotalRecord = 0;
            model.PageSize = PageSize;
            model.ListOfArtist = lstArtists;
            return View("Index", model);

        }
        //
        // GET:/Artist/Create
        [CustomAuthorize(Action = Constants.AdminActions.CreateArtist)]
        public ActionResult Create()
        {
            var countryBL = new CountryBL();
            var lstCountry = new List<Countrys> { new Countrys() };
            lstCountry.AddRange(countryBL.GetAll());
            ViewData["ListCountry"] = lstCountry;

            var bornDiedTextBL = new BornDiedTextBL();
            var lstBornDiedText = new List<BornDiedTextModel> { new BornDiedTextModel() };
            lstBornDiedText.AddRange(bornDiedTextBL.GetAll());
            ViewData["ListBornDiedText"] = lstBornDiedText;
            return View();
        }
        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.CreateArtist)]
        public ActionResult Create(BackEnd.Models.ArtistModel model)
        {
            if (ModelState.IsValid)
            {
                var subsBL = new ArtistBL();
                //var check = subsBL.GetByMenuCode(model.Code);
                //if (check == null)
                //{
                var subs = new Artist();
                subs.FullName = model.FullName;
                subs.FirstName = model.FirstName;
                subs.MiddleName = model.MiddleName;
                subs.LastName = model.LastName;
                if (model.Born > 0)
                    subs.Born = model.Born.Value;
                if (model.Died > 0)
                    subs.Died = model.Died.Value;
                if (model.Country > 0)
                    subs.Country = model.Country;
                if (model.BornDiedTextId > 0)
                    subs.BornDiedTextId = model.BornDiedTextId;
                subs.Affiliate_Id = model.Affiliate_Id;
                subs.DateCreated = DateTime.Now;

                int result = subsBL.CreateArtist(subs);
                if (result > 0)
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData["ErrorMessage"] = "Has an error when executing insert Artist into database";
                }
                //}
                //else
                //{
                //    ViewData["ErrorMessage"] = String.Format("This Artist - {0} exists!", model.Code);

                //}

            }

            var countryBL = new CountryBL();
            var lstCountry = new List<Countrys> { new Countrys() };
            lstCountry.AddRange(countryBL.GetAll());
            ViewData["ListCountry"] = lstCountry;

            var bornDiedTextBL = new BornDiedTextBL();
            var lstBornDiedText = new List<BornDiedTextModel> { new BornDiedTextModel() };
            lstBornDiedText.AddRange(bornDiedTextBL.GetAll());
            ViewData["ListBornDiedText"] = lstBornDiedText;

            return View(model);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [CustomAuthorize(Action = Constants.AdminActions.DeleteArtist)]
        public ActionResult Delete(string id)
        {

            var subsBL = new ArtistBL();
            if (!String.IsNullOrEmpty(id))
            {
                List<string> lstOfSubsIDs = new List<string>();
                foreach (string item in id.Split('_'))
                {
                    int temp = -1;
                    Int32.TryParse(item, out temp);
                    if (temp > 0)
                    {
                        lstOfSubsIDs.Add(item);
                    }
                }
                int result = subsBL.DeleteArtistsByIds(lstOfSubsIDs);
                if (result > 0)
                {
                    //return Json(1, JsonRequestBehavior.AllowGet);
                    ViewData["ErrorMessage"] = "Delete successful!";
                    return RedirectToAction("Index");
                }

            }
            //return Json(0, JsonRequestBehavior.AllowGet);
            ViewData["ErrorMessage"] = "Cannot delete selected items!";
            return RedirectToAction("Index");


        }
        //
        // GET:/Artist/Edit/id
        //[AcceptVerbs(HttpVerbs.Get)]
        [CustomAuthorize(Action = Constants.AdminActions.UpdateArtist)]
        public ActionResult Edit(int id)
        {
            var subBL = new ArtistBL();
            var subs = subBL.GetArtistById(id);
            var subModel = new BackEnd.Models.ArtistModel();

            subModel.ArtistId = subs.ArtistId;

            subModel.FullName = subs.FullName;
            subModel.FirstName = subs.FirstName;
            subModel.MiddleName = subs.MiddleName;
            subModel.LastName = subs.LastName;

            subModel.Born = subs.Born;

            subModel.Died = subs.Died;

            subModel.Country = subs.Country;

            subModel.BornDiedTextId = subs.BornDiedTextId;
            subModel.Affiliate_Id = subs.Affiliate_Id;

            var countryBL = new CountryBL();
            var lstCountry = new List<Countrys> { new Countrys() };
            lstCountry.AddRange(countryBL.GetAll());
            ViewData["ListCountry"] = lstCountry;

            var bornDiedTextBL = new BornDiedTextBL();
            var lstBornDiedText = new List<BornDiedTextModel> { new BornDiedTextModel() };
            lstBornDiedText.AddRange(bornDiedTextBL.GetAll());
            ViewData["ListBornDiedText"] = lstBornDiedText;

            return View("Edit", subModel);
        }
        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.UpdateArtist)]
        public ActionResult Edit(BackEnd.Models.ArtistModel model)
        {
            if (ModelState.IsValid)
            {
                var subsBL = new ArtistBL();
                var check = subsBL.GetArtistById(model.ArtistId);
                if (check != null)
                {
                    var subs = new Artist();
                    subs.ArtistId = model.ArtistId;
                    subs.FullName = model.FullName;
                    subs.FirstName = model.FirstName;
                    subs.MiddleName = model.MiddleName;
                    subs.LastName = model.LastName;
                    if (model.Born > 0)
                        subs.Born = model.Born.Value;
                    if (model.Died > 0)
                        subs.Died = model.Died.Value;
                    if (model.Country > 0)
                        subs.Country = model.Country;
                    if (model.BornDiedTextId > 0)
                        subs.BornDiedTextId = model.BornDiedTextId;
                    subs.Affiliate_Id = model.Affiliate_Id;
                    subs.DateCreated = DateTime.Now;

                    int result = subsBL.UpdateArtist(subs);
                    if (result > 0)
                    {
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        ViewData["ErrorMessage"] = "Has an error when executing insert Artist into database";
                    }
                }
                else
                {
                    ViewData["ErrorMessage"] = String.Format("This Artist - {0} not exists!", model.FullName);

                }

            }


            var countryBL = new CountryBL();
            var lstCountry = new List<Countrys> { new Countrys() };
            lstCountry.AddRange(countryBL.GetAll());
            ViewData["ListCountry"] = lstCountry;

            var bornDiedTextBL = new BornDiedTextBL();
            var lstBornDiedText = new List<BornDiedTextModel> { new BornDiedTextModel() };
            lstBornDiedText.AddRange(bornDiedTextBL.GetAll());
            ViewData["ListBornDiedText"] = lstBornDiedText;
            return View(model);
        }

        //
        // GET:/Artist/ManagePrices
        [CustomAuthorize(Action = Constants.AdminActions.CreateArtist)]
        public ActionResult ManagePrices()
        {
            //var artistBL = new ArtistBL();
            //var lstArtistLeft = new List<ArtistForAdminModel>();
            //lstArtistLeft.AddRange(artistBL.get());
            //ViewData["ListCountry"] = lstCountry;

            //var bornDiedTextBL = new BornDiedTextBL();
            //var lstBornDiedText = new List<BornDiedTextModel> { new BornDiedTextModel() };
            //lstBornDiedText.AddRange(bornDiedTextBL.GetAll());
            //ViewData["ListBornDiedText"] = lstBornDiedText;
            return View();
        }

        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.CreateArtist)]
        public ActionResult ManagePrices(ArtistPriceManagementModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.SelectedArtistRightID != model.SelectedArtistLeftID)
                {
                    var artistBL = new ArtistBL();
                    var priceBL = new PriceBL();
                    //check artist Left and Right
                    var artistLeft = artistBL.GetArtistById(model.SelectedArtistLeftID);
                    var artistRight = artistBL.GetArtistById(model.SelectedArtistRightID);
                    if (artistLeft != null && artistRight != null)
                    {
                        if (String.IsNullOrEmpty(model.SelectedPricesLeft) && String.IsNullOrEmpty(model.SelectedPricesRight))
                        {
                            ModelState.AddModelError("A", "Works in left or right required!");
                            ViewData["ErrorMessage"] = "Works in left or right required!";
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(model.SelectedPricesLeft))
                            {
                                string prices = model.SelectedPricesLeft.Trim(';');
                                if (!String.IsNullOrEmpty(prices))
                                {
                                    prices = prices.Replace(';',',');
                                    priceBL.UpdateArtistIdByIds(prices, artistLeft.ArtistId);
                                }

                            }
                            if (!String.IsNullOrEmpty(model.SelectedPricesRight))
                            {
                                string prices = model.SelectedPricesRight.Trim(';');
                                if (!String.IsNullOrEmpty(prices))
                                {
                                    prices = prices.Replace(';', ',');
                                    priceBL.UpdateArtistIdByIds(prices, artistRight.ArtistId);
                                }

                            }
                            ViewData["ErrorMessage"] = "Update successful!";
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("A", "Selected artist in left or right not exists!");
                        ViewData["ErrorMessage"] = "Selected artist in left or right not exists!";
                    }
                }
                else
                {
                    ModelState.AddModelError("A","Selected artist in left and right must be different!");
                    ViewData["ErrorMessage"] = "Selected artist in left and right must be different!";
                }
            }
            return View();
        }
        
        public ActionResult Autocomplete(string term)
        {
            var artistBL = new ArtistBL();
            var lstArtistLeft = new List<ArtistForAdminModel>();
            lstArtistLeft.AddRange(artistBL.SearchForAdmin(term,-1,-1,-1,1,1000));
            
            return Json(lstArtistLeft.ToArray(), JsonRequestBehavior.AllowGet);
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetWorksByArtist(int id)
        {
            var priceBL = new PriceBL();
            var lstPrices = priceBL.GetByArtistId(id,1,10000);
            //return View();
            //var selectList = new SelectList(lstVeTinh, "SWITCH_CENTRE_CLLI", "SWITCH_CENTRE_NAME");
            return Json(lstPrices.ToArray(), JsonRequestBehavior.AllowGet);

        }


    }
}
